<template>
  <div class="warehouse-management">
    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="success" @click="openAdd">
        <el-icon><Plus /></el-icon>
        新增
      </el-button>
      <el-button type="default" @click="deleteSelected">
        <el-icon><Delete /></el-icon>
        删除
      </el-button>
      <el-button type="default" @click="applyChanges">
        <el-icon><Check /></el-icon>
        应用
      </el-button>
      <el-button type="default" @click="updateData">
        <el-icon><Refresh /></el-icon>
        更新
      </el-button>
      <el-button type="default" @click="exportData">
        <el-icon><Download /></el-icon>
        导出
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="warehouseData"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="warehouseCode" label="仓库编号" width="150">
          <template #default="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">
              {{ scope.row.warehouseCode }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" width="150" />
         <el-table-column prop="warehouseNum" label="库位数量" width="150" />
        <el-table-column prop="warehouseState" label="仓库状态" width="150">
            <template #default="scope">
              <el-tag v-if="scope.row.warehouseState === true" type="success">
               启用
              </el-tag>
              <el-tag v-else type="danger">
               停用
              </el-tag>
            </template>
        </el-table-column>
       <el-table-column prop="operator" label="操作人" width="150" />
       
       
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-link type="primary" @click="editWarehouse(scope.row)">编辑</el-link>
            <el-link type="danger" @click="deleteWarehouse(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    
 

    <!-- 新增仓库-->
      <el-dialog
    v-model="dialogVisible"
    title="新增仓库"
    width="500"
     >
     <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="仓库编号" prop="warehouseCode">
      <el-input v-model="ruleForm.warehouseCode"  disabled  />
    </el-form-item>
     <el-form-item label="仓库名称" prop="warehouseName">
      <el-input v-model="ruleForm.warehouseName" />
    </el-form-item>
    <el-form-item label="仓库数量" prop="warehouseNum">
      <el-input v-model="ruleForm.warehouseNum" />
    </el-form-item>
    <el-form-item label="仓库状态" prop="warehouseState">
      <el-select v-model="ruleForm.warehouseState" placeholder="请选择仓库状态">
        <el-option label="启用" :value="true" />
        <el-option label="停用" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item label="操作人" prop="operator">
      <el-input v-model="ruleForm.operator" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
      </el-dialog>
      

      <!-- 修改仓库-->
      <el-dialog
    v-model="updatedialogVisible"
    title="修改仓库"
    width="500"
     >
     <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="updateWarehouse"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="仓库编号" prop="warehouseCode">
      <el-input v-model="updateWarehouse.warehouseCode"  disabled  />
    </el-form-item>
     <el-form-item label="仓库名称" prop="warehouseName">
      <el-input v-model="updateWarehouse.warehouseName" />
    </el-form-item>
    <el-form-item label="仓库数量" prop="warehouseNum">
      <el-input v-model="updateWarehouse.warehouseNum" />
    </el-form-item>
    <el-form-item label="仓库状态" prop="warehouseState">
      <el-select v-model="updateWarehouse.warehouseState" placeholder="请选择仓库状态">
        <el-option label="启用" :value="true" />
        <el-option label="停用" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item label="操作人" prop="operator">
      <el-input v-model="updateWarehouse.operator" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateWarehouseData()">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
      </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Delete,
  Check,
  Refresh,
  Download
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import moment from 'moment'
import axios from 'axios'

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const selectedRows = ref<WarehouseItem[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
onMounted(() => {
  getWarehouse();
})
// 表单相关


// 仓库数据类型定义
interface WarehouseItem {
  id: number
  warehouseCode: string
  warehouseName: string
  capacity: number
  address: string
  department: string
  manager: string
  locationCount: number
  status: string
  operator: string
  operateTime: string
}

// 仓库数据
const warehouseData = ref<WarehouseItem[]>([])
const getWarehouse = () => {
  axios.get("http://localhost:5198/api/Warehouse/GetWarehouse").then(res=>{
    warehouseData.value=res.data.data;
  })
}
// 方法
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新加载数据
}



const deleteWarehouse = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除仓库 "${row.warehouseName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除API
    const index = warehouseData.value.findIndex(item => item.warehouseCode === row.warehouseCode)
    if (index > -1) {
      warehouseData.value.splice(index, 1)
      ElMessage.success('删除成功!')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const deleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的仓库!')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个仓库吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用批量删除API
    const selectedCodes = selectedRows.value.map(item => item.warehouseCode)
    warehouseData.value = warehouseData.value.filter(item => !selectedCodes.includes(item.warehouseCode))
    ElMessage.success('批量删除成功!')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const applyChanges = () => {
  ElMessage.success('应用成功!')
}

const updateData = () => {
  ElMessage.success('数据更新成功!')
}

const exportData = () => {
  ElMessage.success('导出成功!')
}

const viewDetail = (row: any) => {
  ElMessage.info(`查看仓库详情: ${row.warehouseName}`)
}


//新增

const openAdd=()=>{
   // 生成入库单号：当前时间的年月日时分秒格式
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    
    ruleForm.warehouseCode = `${year}${month}${day}${hours}${minutes}${seconds}`
  dialogVisible.value=true;
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  warehouseName: '',
  warehouseCode: '',
  warehouseNum: '',
  warehouseState: false,
  operator: '',
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive({
  warehouseName: [
    { required: true, message: '仓库名称不能为空', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  warehouseCode: [
    {
      required: true,
      message: '仓库编号不能为空',
      trigger: 'change',
    },
  ],
  warehouseNum: [
    {
      required: true,
      message: '仓库数量不能为空',
      trigger: 'change',
    },
  ],
  warehouseState: [
    {
      type: 'boolean',
      required: true,
      message: '仓库状态不能为空',
      trigger: 'change',
    },
  ],
  operator: [
    {
      required: true,
      message: '操作人不能为空',
      trigger: 'change',
    },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 创建一个包含所有必需字段的、最完整的 payload 对象
      const payload = {
        warehouseName: ruleForm.warehouseName,
        warehouseCode: ruleForm.warehouseCode,
        warehouseNum: Number(ruleForm.warehouseNum),
        warehouseState: ruleForm.warehouseState,
        operator: ruleForm.operator,
        isDelete: false,
        createName: ruleForm.operator, // 通常创建人就是操作人
        updateName: "",
        delName: "",
      };

     axios.post("http://localhost:5230/api/Warehouse/AddWarehouse", payload).then(res=>{
      if(res.data.code==200){
        ElMessage.success('添加成功!')
        ruleForm.operator="";
        ruleForm.warehouseCode="";
        ruleForm.warehouseName="";
        ruleForm.warehouseNum="";
        ruleForm.warehouseState=false;  
        dialogVisible.value=false
        getWarehouse()
      }
      else{
        ElMessage.error(res.data.message)
      }
     })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


const updatedialogVisible=ref(false);
const updateWarehouse=reactive({
  id:0,
  warehouseCode:"",
  warehouseName:"",
  warehouseNum:"",
  warehouseState:false,
  operator:"",
})
const editWarehouse=(row:any)=>{
  updatedialogVisible.value=true;
  updateWarehouse.id=row.id;
  updateWarehouse.warehouseCode=row.warehouseCode;
  updateWarehouse.warehouseName=row.warehouseName;
  updateWarehouse.warehouseNum=row.warehouseNum;
  updateWarehouse.warehouseState=row.warehouseState;
  updateWarehouse.operator=row.operator;
}

const updateWarehouseData = () => {
  // 确保 warehouseNum 是数字类型
  const warehouseNumAsNumber = Number(updateWarehouse.warehouseNum);

  // 检查转换是否有效
  if (isNaN(warehouseNumAsNumber)) {
    ElMessage.error('仓库数量必须是有效的数字');
    return;
  }

  // 精确构建一个与后端 Update DTO 匹配的 payload 对象
  const payload = {
    id: updateWarehouse.id,
    warehouseCode: updateWarehouse.warehouseCode,
    warehouseName: updateWarehouse.warehouseName,
    warehouseNum: warehouseNumAsNumber,
    warehouseState: updateWarehouse.warehouseState,
    operator: updateWarehouse.operator,
    // 根据 working AddWarehouse 推断，这些字段是必需的
    updateName: updateWarehouse.operator,
    isDelete: false,
    createName: "", // 传递空值或从原始数据中获取
    delName: ""      // 传递空值
  };

  console.log('发送到后端的 payload:', JSON.stringify(payload, null, 2));

  axios.put("http://localhost:5230/api/Warehouse/UpdateWarehouse", payload).then(res => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      getWarehouse();
      updatedialogVisible.value = false;
    } else {
      ElMessage.error(res.data.message || '更新失败');
    }
  }).catch(error => {
    console.error("更新仓库失败:", error);
    ElMessage.error('更新仓库失败，请检查网络或联系管理员');
  });
};

</script>

<style scoped>
.warehouse-management {
  padding: 20px;
}

.action-section {
  margin-bottom: 20px;
}

.action-section .el-button {
  margin-right: 10px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.el-table .el-link {
  margin-right: 8px;
}

.el-table .el-link:last-child {
  margin-right: 0;
}
</style>